<template>
  <div class="user-container">
    <!-- 个人信息卡片 -->
    <div class="user-card">
      <div class="card-header">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userData.avatar" class="user-avatar" />
          <div class="upload-overlay">
            <el-upload
              class="avatar-upload"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
            >
              <el-button circle type="primary">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-upload>
          </div>
        </div>
        
        <div class="user-info">
          <h2 class="user-name">{{ userData.name }}</h2>
          <div class="user-contact">
            <div class="contact-item">
              <el-icon><Message /></el-icon>
              <span>{{ userData.email }}</span>
            </div>
            <div class="contact-item">
              <el-icon><Phone /></el-icon>
              <span>{{ userData.phone }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="card-stats">
        <div class="stat-item">
          <div class="stat-value">{{ userData.stats.lost }}</div>
          <div class="stat-label">失物发布</div>
        </div>
        <div class="stat-divider"></div>
        <div class="stat-item">
          <div class="stat-value">{{ userData.stats.found }}</div>
          <div class="stat-label">招领发布</div>
        </div>
        <div class="stat-divider"></div>
        <div class="stat-item">
          <div class="stat-value">{{ userData.stats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area card-shadow">
      <el-tabs v-model="activeTab">
        <!-- 我的发布 -->
        <el-tab-pane label="我的发布" name="posts">
          <div class="tab-header">
            <el-radio-group v-model="postType" size="large">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="lost">失物</el-radio-button>
              <el-radio-button label="found">招领</el-radio-button>
            </el-radio-group>
            <el-button type="primary" @click="handlePublish">
              <el-icon><Plus /></el-icon>发布信息
            </el-button>
          </div>

          <el-table :data="displayPosts" style="width: 100%">
            <el-table-column prop="title" label="标题">
              <template #default="{ row }">
                <div class="post-title" @click="handleViewDetail(row)">
                  {{ row.title }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="发布时间" />
            <el-table-column prop="type" label="类型">
              <template #default="{ row }">
                <el-tag :type="row.type === 'lost' ? 'danger' : 'success'">
                  {{ row.type === 'lost' ? '失物' : '招领' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="success"
                  v-if="row.status === 'active'"
                  @click="handleComplete(row)"
                >
                  完成
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="profile">
          <div class="profile-section">
            <el-form
              ref="profileForm"
              :model="profileData"
              :rules="profileRules"
              label-width="80px"
              class="profile-form"
              :disabled="!isEditing"
            >
              <el-form-item label="用户名" prop="name">
                <el-input 
                  v-model="profileData.name"
                  placeholder="请输入用户名"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input 
                  v-model="profileData.email"
                  placeholder="请输入邮箱地址"
                  type="email"
                />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input 
                  v-model="profileData.phone"
                  placeholder="请输入手机号"
                  maxlength="11"
                />
              </el-form-item>
              <el-form-item label="常用地点" prop="defaultLocation">
                <el-cascader
                  v-model="profileData.defaultLocation"
                  :options="locations"
                  placeholder="请选择常用地点"
                  clearable
                  class="full-width"
                />
              </el-form-item>
            </el-form>
            <div class="form-actions">
              <el-button 
                :type="isEditing ? 'success' : 'primary'"
                @click="handleEditToggle"
                class="submit-btn"
              >
                {{ isEditing ? '保存' : '编辑' }}
              </el-button>
              <el-button 
                v-if="isEditing"
                @click="isEditing = false"
                class="cancel-btn"
              >
                取消
              </el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- 消息通知 -->
        <el-tab-pane label="消息通知" name="notifications">
          <div class="message-filter">
            <el-radio-group v-model="notificationTab" size="large">
              <el-radio-button label="unread">未读消息</el-radio-button>
              <el-radio-button label="all">全部消息</el-radio-button>
            </el-radio-group>
          </div>
          
          <!-- 未读消息列表 -->
          <div v-if="notificationTab === 'unread'">
            <el-empty description="暂无未读消息" v-if="unreadNotifications.length === 0" />
            
            <div class="message-list" v-else>
              <div 
                v-for="notification in unreadNotifications" 
                :key="notification.id"
                class="message-item"
              >
                <div class="message-icon">
                  <el-icon :class="[notification.type]">
                    <component :is="getNotificationIcon(notification.type)" />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-title">{{ notification.title }}</span>
                  </div>
                  <div class="message-body">{{ notification.content }}</div>
                </div>
                <div class="message-actions">
                  <span class="message-time">{{ notification.time }}</span>
                  <el-button type="primary" link class="read-btn" @click="handleMarkAsRead(notification)">
                    标记已读
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 全部消息列表 -->
          <div v-if="notificationTab === 'all'">
            <el-empty description="暂无消息" v-if="allNotifications.length === 0" />
            
            <div class="message-list" v-else>
              <div 
                v-for="notification in allNotifications" 
                :key="notification.id"
                class="message-item"
                :class="{'is-read': notification.isRead}"
              >
                <div class="message-icon">
                  <el-icon :class="[notification.type]">
                    <component :is="getNotificationIcon(notification.type)" />
                  </el-icon>
                  <div class="unread-dot" v-if="!notification.isRead"></div>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-title">{{ notification.title }}</span>
                  </div>
                  <div class="message-body">{{ notification.content }}</div>
                </div>
                <div class="message-actions">
                  <span class="message-time">{{ notification.time }}</span>
                  <el-button v-if="!notification.isRead" type="primary" link class="read-btn" @click="handleMarkAsRead(notification)">
                    标记已读
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  Plus,
  Message,
  Phone,
  Bell,
  ChatDotRound,
  InfoFilled,
  Edit
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 用户数据
const userData = ref({
  avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=1',
  name: '张三',
  email: 'zhangsan@example.com',
  phone: '13800138000',
  stats: {
    lost: 5,
    found: 3,
    completed: 6
  }
})

// 标签页
const activeTab = ref('posts')
const notificationTab = ref('unread')

// 发布列表
const postType = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 模拟发布数据
const posts = [
  {
    id: 1,
    title: 'iPhone 15 Pro',
    time: '2024-03-15 14:30',
    type: 'lost',
    status: 'active',
    image: 'https://picsum.photos/300/200?random=1'
  },
  {
    id: 2,
    title: '学生证',
    time: '2024-03-14 10:20',
    type: 'found',
    status: 'completed',
    image: 'https://picsum.photos/300/200?random=2'
  }
]

// 根据类型筛选发布
const displayPosts = computed(() => {
  if (postType.value === 'all') {
    return posts
  }
  return posts.filter(post => post.type === postType.value)
})

// 个人信息表单
const profileForm = ref<FormInstance>()
const profileData = ref({
  name: '张三',
  email: 'zhangsan@example.com',
  phone: '13800138000',
  defaultLocation: []
})

// 表单编辑状态
const isEditing = ref(false)

// 地点选项
const locations = [
  {
    value: 'teaching',
    label: '教学区',
    children: [
      { value: 'building-a', label: 'A教学楼' },
      { value: 'building-b', label: 'B教学楼' }
    ]
  },
  {
    value: 'living',
    label: '生活区',
    children: [
      { value: 'canteen', label: '食堂' },
      { value: 'dormitory', label: '宿舍区' }
    ]
  }
]

// 表单验证规则
const profileRules = ref<FormRules>({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 模拟消息数据
const unreadNotifications = ref([
  {
    id: 1,
    type: 'comment',
    title: '新的留言',
    content: '有人在您发布的失物信息下留言',
    time: '10分钟前'
  },
  {
    id: 2,
    type: 'system',
    title: '系统通知',
    content: '您的发布已通过审核',
    time: '1小时前'
  }
])

const allNotifications = ref([
  {
    id: 1,
    type: 'comment',
    title: '新的留言',
    content: '有人在您发布的失物信息下留言',
    time: '10分钟前',
    isRead: false
  },
  {
    id: 2,
    type: 'system',
    title: '系统通知',
    content: '您的发布已通过审核',
    time: '1小时前',
    isRead: false
  },
  {
    id: 3,
    type: 'message',
    title: '消息提醒',
    content: '您的物品已被认领',
    time: '1天前',
    isRead: true
  }
])

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    active: 'primary',
    completed: 'success',
    expired: 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    active: '进行中',
    completed: '已完成',
    expired: '已过期'
  }
  return texts[status] || status
}

// 获取通知图标
const getNotificationIcon = (type: string) => {
  const icons: Record<string, any> = {
    comment: ChatDotRound,
    system: InfoFilled,
    message: Bell
  }
  return icons[type] || Bell
}

// 头像上传
const handleAvatarChange = (file: File) => {
  // TODO: 实现头像上传
  console.log('上传头像：', file)
}

// 发布相关
const handlePublish = () => {
  router.push('/publish')
}

const handleViewDetail = (row: any) => {
  router.push(`/detail/${row.id}`)
}

const handleEdit = (row: any) => {
  router.push(`/publish?id=${row.id}`)
}

const handleComplete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认将该信息标记为已完成？')
    // TODO: 调用接口更新状态
    ElMessage.success('操作成功')
  } catch {
    // 用户取消操作
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认删除该信息？', '提示', {
      type: 'warning'
    })
    // TODO: 调用接口删除数据
    ElMessage.success('删除成功')
  } catch {
    // 用户取消操作
  }
}

// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新加载数据
}

// 处理编辑/保存切换
const handleEditToggle = async () => {
  if (isEditing.value) {
    // 保存修改
    if (!profileForm.value) return
    
    try {
      await profileForm.value.validate()
      // TODO: 调用接口保存数据
      ElMessage.success('保存成功')
      isEditing.value = false
    } catch (error) {
      console.log('表单验证失败：', error)
    }
  } else {
    // 进入编辑模式
    isEditing.value = true
  }
}

// 标记消息已读
const handleMarkAsRead = (notification: any) => {
  // TODO: 调用接口标记消息已读
  ElMessage.success('已标记为已读')
}
</script>

<style scoped lang="scss">
.user-container {
  max-width: 1200px;
  min-width: $min-width;
  margin: 0 auto;
  padding: $spacing-huge;
  animation: fadeIn 0.6s ease;
  display: flex;
  flex-direction: column;
  gap: $spacing-huge;
  
  @media (max-width: 768px) {
    padding: $spacing-base;
  }
}

.user-card {
  @include card-style;
  padding: 0;
  overflow: hidden;
}

.card-header {
  position: relative;
  padding: $spacing-huge;
  display: flex;
  align-items: center;
  gap: $spacing-huge;
  background: $background-white;
}

.avatar-container {
  position: relative;
  
  .user-avatar {
    border: 4px solid white;
    box-shadow: $box-shadow-base;
    background: $primary-gradient;
  }
  
  .upload-overlay {
    position: absolute;
    right: 0;
    bottom: 0;
    
    .el-button {
      box-shadow: $box-shadow-base;
      transform: scale(0.8);
      transition: $transition-base;
      
      &:hover {
        transform: scale(0.9);
      }
    }
  }
}

.user-info {
  .user-name {
    font-size: 22px;
    font-weight: 600;
    color: $text-primary;
    margin: 0 0 $spacing-base;
  }
  
  .user-contact {
    display: flex;
    flex-direction: column;
    gap: $spacing-small;
    
    .contact-item {
      display: flex;
      align-items: center;
      gap: $spacing-small;
      color: $text-regular;
      font-size: 14px;
      
      .el-icon {
        color: var(--el-color-primary);
        font-size: 16px;
      }
    }
  }
}

.card-stats {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: $spacing-large $spacing-base;
  background: #f8f9fa;
  border-top: 1px solid $border-lighter;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: $spacing-mini $spacing-small;
  
  .stat-value {
    font-size: 24px;
    font-weight: 600;
    background: $primary-gradient;
    -webkit-background-clip: text;
    color: transparent;
    margin-bottom: $spacing-mini;
  }
  
  .stat-label {
    font-size: 13px;
    color: $text-secondary;
  }
}

.stat-divider {
  width: 1px;
  height: 30px;
  background-color: $border-light;
}

.content-area {
  background: white;
  border-radius: $border-radius-large;
  padding: $spacing-huge;
  min-height: 600px;
  animation: slideLeft 0.6s ease;
  width: 100%;

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #e4e7ed;
  }

  :deep(.el-tabs__active-bar) {
    background: $primary-gradient;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    padding: 0 $spacing-large;
    
    &.is-active {
      color: var(--el-color-primary);
      font-weight: 600;
    }
  }

  :deep(.el-tab-pane) {
    padding: $spacing-large 0;
  }

  .tab-header {
    @include flex-between;
    margin-bottom: $spacing-huge;

    .el-radio-group {
      .el-radio-button {
        margin-right: 2px;
      }
    }

    .el-button {
      background: $primary-gradient;
      border: none;
      padding: $spacing-small $spacing-large;
      height: 40px;
      
      .el-icon {
        margin-right: $spacing-small;
        vertical-align: middle;
      }
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
      }
    }
  }

  :deep(.el-table) {
    border-radius: $border-radius-base;
    overflow: hidden;
    margin-bottom: $spacing-large;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    --el-table-header-bg-color: #f8f9fa;
    table-layout: auto;

    th {
      background-color: #f8f9fa;
      font-weight: 600;
      color: $text-primary;
      padding: $spacing-base $spacing-base;
      height: 50px;
    }

    td {
      padding: $spacing-base $spacing-base;
      height: 60px;
      color: $text-regular;
    }

    .cell {
      padding: 0 $spacing-base;
      line-height: 1.6;
      display: flex;
      align-items: center;
      min-height: 40px;
    }

    .post-title {
      color: var(--el-color-primary);
      cursor: pointer;
      transition: $transition-base;
      font-weight: 500;
      @include text-overflow;

      &:hover {
        color: var(--el-color-primary-light-3);
        text-decoration: underline;
      }
    }

    .el-tag {
      padding: 0 $spacing-base;
      height: 26px;
      line-height: 26px;
      white-space: nowrap;
      display: inline-block;
      text-align: center;
    }

    .el-button-group {
      display: flex;
      justify-content: flex-start;
      gap: $spacing-base;
    }

    .el-button {
      margin: 0;
      font-size: 14px;
      height: 28px;
      line-height: 1;
      padding: 0 $spacing-base;
      
      &.el-button--success,
      &.el-button--danger,
      &.el-button--primary {
        font-weight: 500;
      }
    }
  }
}

.pagination-container {
  margin-top: $spacing-huge;
  @include flex-center;
  
  :deep(.el-pagination) {
    padding: $spacing-base;
    
    .el-pagination__sizes {
      margin-right: $spacing-large;
    }
    
    .el-pagination__jump {
      margin-left: $spacing-large;
    }
    
    button {
      margin: 0 $spacing-mini;
    }
  }
}

.message-filter {
  margin-bottom: $spacing-huge;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: $spacing-base;
}

.message-item {
  display: flex;
  padding: $spacing-base $spacing-base;
  background: white;
  border-radius: $border-radius-base;
  border-left: 3px solid var(--el-color-primary);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  transition: $transition-base;
  min-height: 80px;
  
  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transform: translateY(-1px);
  }
  
  &.is-read {
    border-left-color: $border-light;
    opacity: 0.75;
  }
}

.message-icon {
  margin-right: $spacing-base;
  padding-top: 4px;
  position: relative;
  
  .el-icon {
    font-size: 18px;
    
    &.comment {
      color: #67c23a;
    }
    
    &.system {
      color: #e6a23c;
    }
    
    &.message {
      color: var(--el-color-primary);
    }
  }
  
  .unread-dot {
    position: absolute;
    top: 0;
    right: -2px;
    width: 6px;
    height: 6px;
    background: $danger-color;
    border-radius: 50%;
  }
}

.message-content {
  flex: 1;
  min-width: 0;
  padding: 2px 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-mini;
}

.message-title {
  font-size: 15px;
  font-weight: 500;
  color: $text-primary;
  @include text-overflow;
}

.message-time {
  display: none;
}

.message-body {
  font-size: 13px;
  color: $text-regular;
  line-height: 1.4;
  margin-bottom: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  padding-left: $spacing-large;
  min-width: 90px;
  padding-top: 2px;
  padding-bottom: 2px;
  
  .message-time {
    display: block;
    font-size: 12px;
    color: $text-secondary;
    white-space: nowrap;
    margin-bottom: $spacing-mini;
  }
}

.read-btn {
  font-size: 13px;
  padding: 0;
  height: auto;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideLeft {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.profile-section {
  background: #f8f9fa;
  border-radius: $border-radius-large;
  padding: $spacing-large;
}

.profile-form {
  margin-bottom: $spacing-large;

  :deep(.el-form-item) {
    margin-bottom: $spacing-large;

    .el-form-item__label {
      font-weight: 500;
      color: $text-primary;
    }

    .el-input,
    .el-cascader {
      width: 100%;
      max-width: 100%;

      .el-input__wrapper {
        box-shadow: none;
        border: 2px solid $border-color;
        border-radius: $border-radius-base;
        transition: $transition-base;
        width: 100%;

        &:hover {
          border-color: var(--el-color-primary-light-5);
        }

        &.is-focus {
          border-color: var(--el-color-primary);
          box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
        }
      }

      input {
        height: 40px;
        font-size: 15px;
      }
    }
  }
}

.form-actions {
  display: flex;
  gap: $spacing-base;
  justify-content: center;
  margin-top: $spacing-huge;

  .submit-btn {
    min-width: 120px;
    height: 40px;
    border: none;
    font-size: 15px;
    font-weight: 500;
    padding: 0 $spacing-large;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }

  .cancel-btn {
    min-width: 120px;
    height: 40px;
    font-size: 15px;
    font-weight: 500;
    padding: 0 $spacing-large;
    
    &:hover {
      transform: translateY(-2px);
    }
  }
}
</style> 